package com.wwtech.epp.ui.activity.friend;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.socks.library.KLog;
import com.wwtech.epp.R;
import com.wwtech.epp.application.AppConfig;
import com.wwtech.epp.base.BaseActivity;
import com.wwtech.epp.contain.ContainValue;
import com.wwtech.epp.db.Friend;
import com.wwtech.epp.entity.GroupInfo;
import com.wwtech.epp.entity.eventbus.ModifyGroupInfo;
import com.wwtech.epp.ui.activity.friend.component.DaggerGroupInfoComponent;
import com.wwtech.epp.ui.activity.friend.contract.GroupInfoContract;
import com.wwtech.epp.ui.activity.friend.module.GroupInfoModule;
import com.wwtech.epp.ui.activity.friend.presenter.GroupInfoPresenter;
import com.wwtech.epp.ui.activity.mine.MyInfoActivity;
import com.wwtech.epp.ui.adapter.work.ProjectAdapter;
import com.wwtech.epp.view.ProjectMemberView;


import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Group;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * @author hzp
 * @Package com.wwtech.epp.ui.activity.friend
 * @Description: $description
 * @date 2017/12/06 11:49:09
 */

public class GroupInfoActivity extends BaseActivity implements GroupInfoContract.View {

    @Inject
    GroupInfoPresenter mPresenter;
    @BindView(R.id.flag_nincheng)
    TextView flagNincheng;
    @BindView(R.id.tv_nincheng)
    TextView tvNincheng;
    @BindView(R.id.textView4)
    TextView textView4;
    @BindView(R.id.recycerView)
    RecyclerView recycerView;
    @BindView(R.id.exit_group)
    TextView exitGroup;
    private ProjectAdapter partMamberAdapter;

    public static final int EDITTEXT = 0;
    public static final int ADDMEMBER = 1;
    public static final int DELETMEMBER = 2;

    private boolean isCheck = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_group_info);
        ButterKnife.bind(this);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    protected void initData() {
        setTitle("群组设置");
        mPresenter.getGroupInfo(getIntent().getStringExtra("id"), new HashMap<String, String>());
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 5);
        recycerView.setNestedScrollingEnabled(false);
        gridLayoutManager.setSmoothScrollbarEnabled(true);
        gridLayoutManager.setAutoMeasureEnabled(true);
        recycerView.setLayoutManager(gridLayoutManager);
        recycerView.setHasFixedSize(true);
        recycerView.setNestedScrollingEnabled(false);
    }

    @Override
    protected void setupActivityComponent() {
        DaggerGroupInfoComponent
                .builder()
                .appComponent(((AppConfig) getApplication()).getApplicationComponent())
                .groupInfoModule(new GroupInfoModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void setPresenter(GroupInfoContract.GroupInfoContractPresenter presenter) {
        mPresenter = (GroupInfoPresenter) presenter;
    }


    @Override
    public void showProgressDialog() {
        progressDialog.show();
    }

    @Override
    public void closeProgressDialog() {
        progressDialog.hide();
    }

    @Override
    public void setGroupInfo(GroupInfo groupInfo) {
        tvNincheng.setText(groupInfo.getData().getGroupName());
        Friend friend = new Friend("-1", "添加", Uri.parse(""), "添加");
        Friend friendDelet = new Friend("-2", "删除", Uri.parse("delet"), "删除");
        friend.setUserId("-1");
        friendDelet.setUserId("-2");
        if (ContainValue.userLogin.getData().getUserId() == groupInfo.getData().getGroupOwnUserId()) {
            groupInfo.getData().getGroupUsersProfile().add(friend);
            groupInfo.getData().getGroupUsersProfile().add(friendDelet);
        }
        if (partMamberAdapter == null) {
            partMamberAdapter = new ProjectAdapter(groupInfo.getData().getGroupUsersProfile());
            recycerView.setAdapter(partMamberAdapter);
            partMamberAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                    ProjectMemberView projectMemberView = (ProjectMemberView) view;
                    if (partMamberAdapter.getData().get(i).getUserId().equals("-1")) {
                        Intent intent = new Intent(GroupInfoActivity.this, AddPersonActivity.class);
                        intent.putExtra("title", "添加群成员");
                        startActivityForResult(intent, ADDMEMBER);
                    } else if (partMamberAdapter.getData().get(i).getUserId().equals("-2")) {
                        ContainValue.partPerson = new ArrayList<>();
                        Intent intent = new Intent(GroupInfoActivity.this, FriendListActivity.class);
                        intent.putExtra("flag", "");
                        intent.putExtra("name", "删除群成员");
                        intent.putExtra("id", getIntent().getStringExtra("id"));
                        startActivityForResult(intent, DELETMEMBER);
                    } else {
                        if (("" + ContainValue.userLogin.getData().getUserId()).equals(friend.getUserId())) {
                            Intent intent = new Intent(GroupInfoActivity.this, MyInfoActivity.class);
                            startActivity(intent);
                        } else {
                            Intent intent = new Intent(GroupInfoActivity.this, UserDetailActivity.class);
                            intent.putExtra("friend", partMamberAdapter.getData().get(i));
                            startActivity(intent);
                        }
                    }
                }
            });
        }
        partMamberAdapter.setNewData(groupInfo.getData().getGroupUsersProfile());
        if (isCheck) {
            Group group = new Group(groupInfo.getData().getGroupId() + "", groupInfo.getData().getGroupName(), Uri.parse(groupInfo.getData().getGroupAvatar()));
            EventBus.getDefault().post(new ModifyGroupInfo(group));

            RongIM.getInstance().refreshGroupInfoCache(group);
        }

        for (int i = 0; i < groupInfo.getData().getGroupUsersProfile().size(); i++) {
            if ((ContainValue.userLogin.getData().getUserId() + "").equals(groupInfo.getData().getGroupUsersProfile().get(i).getUserId())) {
                return;
            }
        }
        flagNincheng.setClickable(false);
        exitGroup.setVisibility(View.GONE);
    }

    @Override
    public void modifySuccess() {
        initData();
        isCheck = true;
    }

    @Override
    protected void onDestroy() {
        ContainValue.currentGroupMember = null;
        super.onDestroy();
    }

    private void preDeleteMember(Friend friend) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 20) {
            if (requestCode == EDITTEXT) {
                tvNincheng.setText(data.getStringExtra("content"));
                preModifyGroup(data.getStringExtra("content"));
            } else if (requestCode == ADDMEMBER) {
                preAddGroupMember();
            } else if (requestCode == DELETMEMBER) {
                preDeleteGroupMember();
            }
        }
    }

    private void preModifyGroup(String groupName) {
        Map<String, RequestBody> map = new HashMap<>();
        MediaType textType = MediaType.parse("text/plain");
        map.put("ownerUid", RequestBody.create(textType, ContainValue.userLogin.getData().getUserId() + ""));
        map.put("groupName", RequestBody.create(textType, groupName));
        map.put("groupId", RequestBody.create(textType, getIntent().getStringExtra("id")));
        mPresenter.editGroupInfo(map);
    }

    private void preDeleteGroupMember() {
        Map<String, String> map = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < ContainValue.partPerson.size(); i++) {
            sb.append(ContainValue.partPerson.get(i).getUserId() + ",");
        }
        map.put("userIds", sb.substring(0, sb.length() - 1));
        KLog.i(sb.substring(0, sb.length() - 1));
        mPresenter.deldeteGroupMember(getIntent().getStringExtra("id"), map);
        ContainValue.partPerson = null;
    }

    private void preAddGroupMember() {
        Map<String, String> map = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < ContainValue.partPerson.size(); i++) {
            sb.append(ContainValue.partPerson.get(i).getUserId() + ",");
        }

        map.put("userIds", sb.substring(0, sb.length() - 1));
        mPresenter.addGroupMember(getIntent().getStringExtra("id"), map);
        ContainValue.partPerson = null;
    }

    @OnClick({R.id.flag_nincheng, R.id.exit_group})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.flag_nincheng:
                mPresenter.editGroupName();
                break;
            case R.id.exit_group:
                preExitGroup();
                break;
            default:

                break;
        }
    }

    private void preExitGroup() {
        Map<String, String> map = new HashMap<>();
        map.put("userId", ContainValue.userLogin.getData().getUserId() + "");
        map.put("groupId", getIntent().getStringExtra("id"));
        mPresenter.quitGroup(map);
    }

    @Override
    public void qiutGroupSuccess() {
        AppConfig.instance.mAppActivityManager.finishActivity(ConversationActivity.class);
        EventBus.getDefault().post(new ModifyGroupInfo());
        finish();
    }
}